package cn.iot.controller;

import cn.iot.common.api.CommonResult;
import cn.iot.common.utils.StringUtils;
import cn.iot.domain.Floor;
import cn.iot.domain.Loudong;
import cn.iot.domain.Room;
import cn.iot.service.FloorService;
import cn.iot.service.LoudongService;
import cn.iot.service.RoomService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/floor")
public class FloorController {
    @Autowired
    FloorService floorService;
    @Autowired
    LoudongService loudongService;
    @PostMapping("/getList")
    public CommonResult getList(Integer loudongId,String floorName){
        LambdaQueryWrapper<Floor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(floorName),Floor::getFloorName,floorName);
        queryWrapper.eq(Floor::getLoudongId,loudongId);
        List<Floor> list = floorService.list(queryWrapper);
        return CommonResult.success(list);
    }
    @PostMapping("/saveOrUpdate")
    public CommonResult saveOrUpdate(@RequestBody Floor floor){
        Integer id = floor.getId();
        Floor f=new Floor();
        if(id!=null){
            f=floorService.getById(id);
        }

        floorService.saveOrUpdate(floor);
        if(id==null){
            //新增 把楼栋里的楼层数加一
            Loudong loudong = loudongService.getById(floor.getLoudongId());
            if(loudong.getLoudongNum()==null){
                loudong.setLoudongNum(1);
            }else {
                loudong.setLoudongNum(loudong.getLoudongNum()+1);
            }

            loudongService.saveOrUpdate(loudong);
        }

        if (id==null&&floor.getRoomNum()!=null||floor.getRoomNum()!=f.getRoomNum()) {
            for (int i = 1; i <= floor.getRoomNum(); i++) {
                Room room = new Room();
                room.setFloorId(floor.getId());
                room.setRoomId(i);
                room.setRoomName(i+"间");
                roomService.saveOrUpdate(room);
            }
        }
        return CommonResult.success();
    }
    @Autowired
    RoomService roomService;
    @DeleteMapping("/del/{id}")
    public CommonResult deleteById(@PathVariable Integer id){
        Floor floor = floorService.getById(id);

        Loudong loudong = loudongService.getById(floor.getLoudongId());
        loudong.setLoudongNum(loudong.getLoudongNum()-1);
        loudongService.saveOrUpdate(loudong);

        LambdaQueryWrapper<Room> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Room::getFloorId,id);
        List<Room> rooms = roomService.list(wrapper);
        for (Room room : rooms) {
            roomService.removeById(room.getId());
        }
        floorService.removeById(id);
        return CommonResult.success();
    }
}
